package com.wj.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.wj.dto.RespPageDTO;
import com.wj.pojo.*;
import com.wj.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author wj
 * @since 2022-03-06
 */
@RequiredArgsConstructor
@Api(tags = "员工控制器")
@RestController
@RequestMapping("/employee/basic")
public class EmployeeController {

    private final INationService nationService;
    private final IPoliticsStatusService politicsStatusService;
    private final IPositionService positionService;
    private final IDepartmentService departmentService;
    private final IJoblevelService joblevelService;
    private final IEmployeeService employeeService;

    @ApiOperation("导入员工信息")
    @PostMapping("/import")
    public RespBean importEmployee(MultipartFile file) {
        ImportParams importParams = new ImportParams();
        //去掉标题行
        importParams.setTitleRows(1);
        List<Employee> employees=null;

        //查出所有有外键的属性对应表
        List<Nation> nationList = nationService.list();
        List<PoliticsStatus> politicsStatusList = politicsStatusService.list();
        List<Department> departmentList = departmentService.list();
        List<Joblevel> joblevelList = joblevelService.list();
        List<Position> positionList = positionService.list();

        try {
            employees = ExcelImportUtil.importExcel(file.getInputStream(), Employee.class, importParams);
            employees.forEach(employee -> {
                //获取外键的id值并赋值
                int i = politicsStatusList.indexOf(new PoliticsStatus(employee.getPoliticsStatus().getName()));
                System.out.println(i);
                employee.setNationId(nationList.get(nationList.indexOf(new Nation(employee.getNation().getName()))).getId());
                employee.setPoliticId(politicsStatusList.get(politicsStatusList.indexOf(
                        new PoliticsStatus(employee.getPoliticsStatus().getName()))).getId());
                employee.setDepartmentId(departmentList.get(departmentList.indexOf(
                        new Department(employee.getDepartment().getName()))).getId());
                employee.setJobLevelId(joblevelList.get(joblevelList.indexOf(
                        new Joblevel(employee.getJoblevel().getName()))).getId());
                employee.setPosId(positionList.get(positionList.indexOf(
                        new Position(employee.getPosition().getName()))).getId());
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (employeeService.saveBatch(employees)){
            return RespBean.success("导入成功");
        }

        return RespBean.error("导入失败");
    }

    @ApiOperation(value = "导出员工信息")
    @GetMapping(value = "/export", produces = "application/octet-stream")
    public void exportEmployee(HttpServletResponse resp) {
        List<Employee> employees = employeeService.getAllEmployeeById(null);
        ExportParams exportParams = new ExportParams("员工表", "员工表", ExcelType.HSSF);
        Workbook sheets = ExcelExportUtil.exportExcel(exportParams, Employee.class, employees);

        try {
            //流形式
            resp.setHeader("content-type", "application/octet-stream;charset=utf-8");
            //导出文件名
            resp.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode("员工表.xls", "UTF-8"));
            sheets.write(resp.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @ApiOperation(value = "获取所有员工（分页）")
    @GetMapping("/")
    public RespPageDTO getAllEmployee(@RequestParam(defaultValue = "1") Integer currentPage,
                                      @RequestParam(defaultValue = "10") Integer size,
                                      Employee employee,
                                      @DateTimeFormat(pattern="yyyy-MM-dd")LocalDate[] beginDateScope) {
        System.out.println(employee);
        System.out.println(Arrays.toString(beginDateScope));
        return employeeService.getAllEmployee(currentPage, size, employee, beginDateScope);
    }

    @ApiOperation("添加员工")
    @PostMapping("/")
    public RespBean addEmployee(@RequestBody Employee employee) {
        return employeeService.addEmployee(employee);
    }

    @ApiOperation("更改员工")
    @PutMapping("/")
    public RespBean upEmployee(@RequestBody Employee employee) {
        if (employeeService.updateById(employee)) {
            return RespBean.success("更改成功");
        }
        return RespBean.error("更改失败");
    }

    @ApiOperation("删除员工")
    @DeleteMapping("/{id}")
    public RespBean upEmployee(@PathVariable Integer id) {
        if (employeeService.removeById(id)) {
            return RespBean.success("删除成功");
        }
        return RespBean.error("删除失败");
    }

    @ApiOperation(value = "获取工号")
    @GetMapping("/maxWorkID")
    public RespBean maxWorkID() {
        return employeeService.maxWorkID();
    }

    @ApiOperation(value = "获取所有民族")
    @GetMapping("/nations")
    public List<Nation> getAllNations() {
        return nationService.list();
    }

    @ApiOperation(value = "获取所有职位")
    @GetMapping("/positions")
    public List<Position> getAllPositions() {
        return positionService.list();
    }

    @ApiOperation(value = "获取所有部门")
    @GetMapping("/departments")
    public List<Department> getAllDepartments() {
        return departmentService.getAllDepartments();
    }

    @ApiOperation(value = "获取所有政治面貌")
    @GetMapping("/politicsStatus")
    public List<PoliticsStatus> getAllPoliticsStatus() {
        return politicsStatusService.list();
    }

    @ApiOperation(value = "获取所有职称")
    @GetMapping("/joblevels")
    public List<Joblevel> getAllJoblevels() {
        return joblevelService.list();
    }


}
